import toolMgr from '@/biz/base/tool.js'
import { Message } from 'view-design'
import oss from '@/config/oss'

function image(opt = {}, info = {}) {
  // key title itemName itemUrl
  let api = toolMgr.unloadFile()
  let files = []
  let itemName = opt.itemName ?? 'name'
  let itemUrl = opt.itemUrl ?? 'url'
  if (info[opt.key]?.length > 0) {
    files = info[opt.key].map((item) => {
      return {
        name: item[itemName],
        url: item[itemUrl]
      }
    })
  }
  return {
    title: opt.title,
    key: opt.key,
    visible: opt.visible == false ? false : true,
    uploadImg: {
      title: opt.title,
      api,
      files,
      multiple: opt.multiple ?? false,
      show: opt.show ?? false,
      hideDel: opt.hideDel ?? false,
      maxlength: opt.maxlength ?? 10,
      format: opt.format || ['jpg', 'jpeg', 'png']
    },
    rules: opt.rules,
    data: {
      to: (v) => {
        return {
          [opt.key]: v.map((item) => {
            return {
              [itemName]: item.name,
              [itemUrl]: item.response ? item.response.data.imageURL : item.url
            }
          })
        }
      }
    }
  }
}

function video(opt = {}, info = {}) {
  // key title itemName itemUrl
  let api = toolMgr.unloadFile()
  let files = []
  let itemName = opt.itemName ?? 'name'
  let itemUrl = opt.itemUrl ?? 'url'
  if (info[opt.key]?.length > 0) {
    files = info[opt.key].map((item) => {
      return {
        name: item[itemName],
        url: item[itemUrl]
      }
    })
  }
  let uploadImg = {
    title: opt.title,
    type: 'video',
    api,
    files,
    multiple: opt.multiple ?? false,
    show: opt.show ?? false,
    hideDel: opt.hideDel ?? false,
    maxlength: opt.maxlength ?? 10,
    percent: 0,
    format: ['mp4'],
    maxSize: 1048576,
    before: (file) => {
      oss
        .uploadVideo(file, (res) => {
          uploadImg.percent = Math.round(res * 100)
        })
        .then((res) => {
          info[opt.key] = [
            ...info[opt.key],
            {
              [itemName]: res.name,
              [itemUrl]: res.url
            }
          ]
        })
      return false
    }
  }
  return {
    title: opt.title,
    key: opt.key,
    uploadImg,
    rules: opt.rules,
    data: {
      to: (v) => {
        return {
          [opt.key]: v.map((item) => {
            return {
              [itemName]: item.name,
              [itemUrl]: item.response ? item.response.data.imageURL : item.url
            }
          })
        }
      }
    }
  }
}

export default {
  image,
  video
}
